<template>
  <div class="record-requests">
    <header class="mb-8">
      <h1 class="glow-text">请求记录</h1>
      <div class="tech-line mt-2"></div>
    </header>

    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center">
        <div class="relative">
          <input
            type="text"
            class="input pr-10"
            placeholder="搜索请求..."
            v-model="searchQuery"
          />
          <svg class="w-5 h-5 absolute right-3 top-2.5 text-light-dark" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
          </svg>
        </div>

        <div class="ml-4">
          <select class="input bg-dark-darker" v-model="methodFilter">
            <option value="all">所有方法</option>
            <option value="GET">GET</option>
            <option value="POST">POST</option>
            <option value="PUT">PUT</option>
            <option value="DELETE">DELETE</option>
          </select>
        </div>

        <div class="ml-4">
          <select class="input bg-dark-darker" v-model="statusFilter">
            <option value="all">所有状态码</option>
            <option value="2xx">2xx (成功)</option>
            <option value="3xx">3xx (重定向)</option>
            <option value="4xx">4xx (客户端错误)</option>
            <option value="5xx">5xx (服务器错误)</option>
          </select>
        </div>
      </div>

      <div class="flex space-x-2">
        <button @click="fetchRequests" class="btn btn-outline">
          <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
          </svg>
          刷新
        </button>
      </div>
    </div>

    <div v-if="loading" class="flex justify-center items-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>

    <div v-else-if="filteredRequests.length === 0" class="text-center py-12 text-light-dark">
      暂无请求记录
    </div>

    <div v-else class="overflow-x-auto">
      <table class="w-full">
        <thead>
          <tr class="border-b border-dark-light">
            <th class="py-3 px-4 text-left">服务</th>
            <th class="py-3 px-4 text-left">路径</th>
            <th class="py-3 px-4 text-left">方法</th>
            <th class="py-3 px-4 text-left">状态码</th>
            <th class="py-3 px-4 text-left">响应时间</th>
            <th class="py-3 px-4 text-left">记录时间</th>
            <th class="py-3 px-4 text-left">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="request in filteredRequests"
            :key="request._id"
            class="border-b border-dark-light hover:bg-dark-darker"
          >
            <td class="py-3 px-4">{{ request.service_name }}</td>
            <td class="py-3 px-4 font-mono text-sm truncate max-w-xs">{{ request.path }}</td>
            <td class="py-3 px-4">
              <span :class="{
                'badge badge-blue': request.method === 'GET',
                'badge badge-green': request.method === 'POST',
                'badge badge-purple': request.method === 'PUT',
                'badge badge-orange': request.method === 'DELETE',
                'badge badge-yellow': !['GET', 'POST', 'PUT', 'DELETE'].includes(request.method)
              }">{{ request.method }}</span>
            </td>
            <td class="py-3 px-4">
              <span :class="{
                'text-accent-blue': request.status_code < 300,
                'text-accent-yellow': request.status_code >= 300 && request.status_code < 400,
                'text-accent-orange': request.status_code >= 400 && request.status_code < 500,
                'text-accent-pink': request.status_code >= 500
              }">{{ request.status_code }}</span>
            </td>
            <td class="py-3 px-4">{{ request.response_time.toFixed(2) }} ms</td>
            <td class="py-3 px-4 text-light-dark">{{ formatTime(request.created_at) }}</td>
            <td class="py-3 px-4">
              <router-link :to="`/record/requests/${request._id}`" class="text-primary hover:text-primary-light mr-2" title="查看详情">
                <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                </svg>
              </router-link>
              <button
                @click="convertToDefinition(request._id)"
                class="text-accent-blue hover:text-accent-blue/80 mr-2"
                title="转换为请求定义"
              >
                <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2"></path>
                </svg>
              </button>
              <button
                @click="deleteRequest(request._id)"
                class="text-accent-pink hover:text-accent-pink/80"
                title="删除"
              >
                <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                </svg>
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 分页 -->
      <div class="flex justify-between items-center mt-6">
        <div class="text-light-dark">
          共 {{ pagination.total }} 条记录，第 {{ pagination.page }} / {{ pagination.pages }} 页
        </div>
        <div class="flex space-x-2">
          <button
            @click="changePage(pagination.page - 1)"
            class="btn btn-outline py-1 px-3"
            :disabled="pagination.page <= 1"
          >
            上一页
          </button>
          <button
            @click="changePage(pagination.page + 1)"
            class="btn btn-outline py-1 px-3"
            :disabled="pagination.page >= pagination.pages"
          >
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 转换成功提示 -->
    <div v-if="showConvertSuccess" class="fixed inset-0 bg-dark-darker bg-opacity-75 flex items-center justify-center z-50">
      <div class="bg-dark-light rounded-lg w-full max-w-lg cyber-border">
        <div class="p-6">
          <div class="flex justify-between items-start mb-6">
            <h2 class="text-2xl font-bold">转换成功</h2>
            <button @click="showConvertSuccess = false" class="text-light-dark hover:text-primary">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <div class="mb-6">
            <p>请求记录已成功转换为请求定义。</p>
          </div>

          <div class="flex justify-end">
            <button @click="showConvertSuccess = false" class="btn btn-outline mr-2">关闭</button>
            <router-link :to="`/request/definitions/${convertedDefinitionId}`" class="btn btn-primary">
              查看请求定义
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { recordApi } from '../../api';

// 路由
const router = useRouter();

// 状态变量
const loading = ref(false);
const searchQuery = ref('');
const methodFilter = ref('all');
const statusFilter = ref('all');
const showConvertSuccess = ref(false);
const convertedDefinitionId = ref('');

// 请求记录列表
const requests = ref<any[]>([]);

// 分页
const pagination = ref({
  page: 1,
  page_size: 10,
  total: 0,
  pages: 1
});

// 过滤请求
const filteredRequests = computed(() => {
  let result = requests.value;

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(request =>
      request.service_name?.toLowerCase().includes(query) ||
      request.path?.toLowerCase().includes(query)
    );
  }

  // 方法过滤
  if (methodFilter.value !== 'all') {
    result = result.filter(request => request.method === methodFilter.value);
  }

  // 状态码过滤
  if (statusFilter.value !== 'all') {
    const statusRange = statusFilter.value.charAt(0);
    result = result.filter(request => {
      const statusFirstDigit = Math.floor(request.status_code / 100);
      return statusFirstDigit.toString() === statusRange;
    });
  }

  return result;
});

// 获取请求记录列表
const fetchRequests = async () => {
  try {
    loading.value = true;
    const response = await recordApi.getRequests({
      page: pagination.value.page,
      page_size: pagination.value.page_size
    });
    
    if (response && typeof response === 'object') {
      if (Array.isArray(response.requests)) {
        requests.value = response.requests.map((req: any) => ({
          ...req,
          response_time: req.response_time || 0
        }));
      }
      
      pagination.value = {
        page: response.page || 1,
        page_size: response.page_size || 10,
        total: response.total || 0,
        pages: response.pages || 1
      };
    } else {
      // 模拟数据
      requests.value = [
        {
          _id: '1',
          service_id: '1',
          service_name: 'user-service',
          path: '/api/users/123',
          method: 'GET',
          status_code: 200,
          response_time: 45.2,
          created_at: new Date(Date.now() - 120000).toISOString()
        },
        {
          _id: '2',
          service_id: '2',
          service_name: 'order-service',
          path: '/api/orders',
          method: 'POST',
          status_code: 201,
          response_time: 78.5,
          created_at: new Date(Date.now() - 180000).toISOString()
        },
        {
          _id: '3',
          service_id: '3',
          service_name: 'payment-service',
          path: '/api/payments/456',
          method: 'PUT',
          status_code: 204,
          response_time: 32.1,
          created_at: new Date(Date.now() - 240000).toISOString()
        },
        {
          _id: '4',
          service_id: '1',
          service_name: 'user-service',
          path: '/api/users/789',
          method: 'DELETE',
          status_code: 404,
          response_time: 12.8,
          created_at: new Date(Date.now() - 300000).toISOString()
        },
        {
          _id: '5',
          service_id: '2',
          service_name: 'order-service',
          path: '/api/orders/status',
          method: 'GET',
          status_code: 500,
          response_time: 156.3,
          created_at: new Date(Date.now() - 360000).toISOString()
        }
      ];
      
      pagination.value = {
        page: 1,
        page_size: 10,
        total: requests.value.length,
        pages: 1
      };
    }
  } catch (error) {
    console.error('获取请求记录列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 切换页码
const changePage = (page: number) => {
  if (page < 1 || page > pagination.value.pages) return;
  pagination.value.page = page;
  fetchRequests();
};

// 转换为请求定义
const convertToDefinition = async (id: string) => {
  try {
    const response = await recordApi.convertToDefinition(id);
    
    if (response && response.definition_id) {
      convertedDefinitionId.value = response.definition_id;
      showConvertSuccess.value = true;
    } else {
      // 模拟成功
      convertedDefinitionId.value = '123456';
      showConvertSuccess.value = true;
    }
  } catch (error: any) {
    console.error('转换为请求定义失败:', error);
    alert(`转换为请求定义失败: ${error.response?.data?.error || error.message}`);
  }
};

// 删除请求记录
const deleteRequest = async (id: string) => {
  if (!confirm('确定要删除该请求记录吗？此操作不可恢复。')) return;

  try {
    await recordApi.deleteRequest(id);
    fetchRequests();
  } catch (error: any) {
    console.error('删除请求记录失败:', error);
    alert(`删除请求记录失败: ${error.response?.data?.error || error.message}`);
  }
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '未知';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};

// 监听过滤器变化
watch([searchQuery, methodFilter, statusFilter], () => {
  // 如果过滤器变化，重置到第一页
  if (pagination.value.page !== 1) {
    pagination.value.page = 1;
    fetchRequests();
  }
});

// 生命周期钩子
onMounted(() => {
  fetchRequests();
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
